package com.jrx.anytxn.common.uitl;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

/**
 * Sftp 工具类
 */
public class SftpUtils {

    private static Logger logger = LoggerFactory.getLogger(SftpUtils.class);


    public static Session session;
    public static ChannelSftp channelSftp;

    //打开连接
    public static void sftpConnect(String username,String password,String host,int port) throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
    }

    //关闭连接
    public static void disSftpConnect(){
        if (channelSftp != null) {
            if (channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    //创建目录
    public static void createDir(String createpath) throws SftpException {
        if (isDirExist(createpath)) {
            channelSftp.cd(createpath);
            return;
        }
        String pathArry[] = createpath.split("/");
        StringBuffer filePath = new StringBuffer("/");
        for (String path : pathArry) {
            if (path.equals("")) {
                continue;
            }
            filePath.append(path + "/");
            if (isDirExist(filePath.toString())) {
                channelSftp.cd(filePath.toString());
            } else {
                channelSftp.mkdir(filePath.toString());
                channelSftp.cd(filePath.toString());
            }
        }
        channelSftp.cd(createpath);
    }

    public static boolean isFileExist(String path, String fileName) {
        boolean isFileExist = false;
        try {
            Vector vector = SftpUtils.channelSftp.ls(path);
            for (int i = 0; i < vector.size(); i++) {
                Object obj = vector.elementAt(i);
                if (obj instanceof ChannelSftp.LsEntry) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;
                    if (fileName.equals(entry.getFilename())) {
                        isFileExist = true;
                        break;
                    }
                    logger.info("{}不存在{}",path,fileName);
                }
            }
        } catch (Exception e) {
            return false;
        }
        return isFileExist;
    }

    public static boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = channelSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    //上传文件
    public static void sftpUpload(File uploadFile) throws SftpException, IOException {
        FileInputStream fileInputStream = new FileInputStream(uploadFile);
        channelSftp.put(fileInputStream, uploadFile.getName());
        fileInputStream.close();
    }

    //下载文件
    public static void download(String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
        File file = new File(saveFile);
        channelSftp.get(downloadFile, new FileOutputStream(file));
    }
}
